package utils

import (
	"crypto/tls"
	"errors"
	"fmt"
	"gitee.com/goexc/ddns/variables"
	"io/ioutil"
	"net"
	"net/http"
	"time"
)

// 解析公网IP的服务器
const GLOBAL_IP_SERVER = "https://ifconfig.me/ip"

// 获取公网IP
func IPGlobal() (string, error) {
	variables.Msg <- fmt.Sprintf("公网ip api：%s", GLOBAL_IP_SERVER)
	timeout := time.Duration(10 * time.Second) //超时时间50ms
	client := &http.Client{
		Timeout: timeout,
		Transport: &http.Transport{
			TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
		},
	}

	resp, err := client.Get(GLOBAL_IP_SERVER)
	if err != nil {
		fmt.Println(err)
		variables.Msg <- fmt.Sprintf("公网ip api：%s", GLOBAL_IP_SERVER)
		return "", nil
	}
	defer resp.Body.Close()
	content, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	return IPMatch(string(content))
}

// 判断公网IP是否符合规则
func IPMatch(str string) (ip string, err error) {
	if ip := net.ParseIP(str); ip != nil {
		variables.Msg <- fmt.Sprintf("公网IP:%s", ip.String())
		return ip.String(), nil
	} else {
		return "", errors.New("ip地址不符合规则")
	}
}
